import Foundation
import CoreLocation

// MARK: - 简单坐标测试

func testSimpleCoordinate() {
    let latitude = 35.92277166666667
    let longitude = 139.48274166666667
    
    print("🧪 === 简单坐标测试 ===")
    print("📍 坐标: \(latitude), \(longitude)")
    
    // 验证坐标有效性
    let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    if CLLocationCoordinate2DIsValid(coordinate) {
        print("✅ 坐标有效")
    } else {
        print("❌ 坐标无效")
        return
    }
    
    // 测试苹果地理编码
    let geocoder = CLGeocoder()
    let location = CLLocation(latitude: latitude, longitude: longitude)
    
    print("🍎 开始苹果地理编码测试...")
    geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
        if let error = error {
            print("❌ 苹果地理编码失败: \(error.localizedDescription)")
            print("❌ 错误代码: \(error)")
        } else if let placemarks = placemarks, !placemarks.isEmpty {
            let placemark = placemarks.first!
            print("✅ 苹果地理编码成功:")
            print("   - 国家: \(placemark.country ?? "未知")")
            print("   - 省份: \(placemark.administrativeArea ?? "未知")")
            print("   - 城市: \(placemark.locality ?? "未知")")
            print("   - 区县: \(placemark.subLocality ?? "未知")")
            print("   - 街道: \(placemark.thoroughfare ?? "未知")")
            print("   - 详细地址: \(placemark.subThoroughfare ?? "未知")")
            print("   - 邮政编码: \(placemark.postalCode ?? "未知")")
            print("   - ISO国家代码: \(placemark.isoCountryCode ?? "未知")")
        } else {
            print("❌ 苹果地理编码未找到地址信息")
        }
    }
    
    // 测试OpenStreetMap（免费服务）
    print("🌍 开始OpenStreetMap测试...")
    let osmUrlString = "https://nominatim.openstreetmap.org/reverse?lat=\(latitude)&lon=\(longitude)&format=json&accept-language=zh-CN"
    
    guard let osmUrl = URL(string: osmUrlString) else {
        print("❌ 无效OpenStreetMap URL")
        return
    }
    
    URLSession.shared.dataTask(with: osmUrl) { data, response, error in
        if let error = error {
            print("❌ OpenStreetMap网络请求失败: \(error.localizedDescription)")
            return
        }
        
        guard let data = data else {
            print("❌ OpenStreetMap无响应数据")
            return
        }
        
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            print("✅ OpenStreetMap响应:")
            print("   - 原始数据: \(json)")
            
            if let dict = json as? [String: Any] {
                if let displayName = dict["display_name"] as? String {
                    print("   - 显示名称: \(displayName)")
                }
                if let address = dict["address"] as? [String: Any] {
                    print("   - 地址详情: \(address)")
                }
            }
        } catch {
            print("❌ OpenStreetMap JSON解析失败: \(error)")
        }
    }.resume()
}

// 运行测试
// testSimpleCoordinate() 